package com.hoperun.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hoperun.bean.AdminManager;
import com.hoperun.service.IAdminManagerSV;

/**
 * .
 * <p/>
 * 
 * @author <a href="mailto:1988fuyu@163.com">fuyu</a>
 * @version V1.0, 2012-12-13
 */
@Component
public class LoginHelper {

	private static IAdminManagerSV adminManagerSV;

	@Autowired
	public void init(IAdminManagerSV adminManagerSV) {
		LoginHelper.adminManagerSV = adminManagerSV;
	}

	public static Long getLoginUserId() {
		Subject currentUser = SecurityUtils.getSubject();
		AdminManager user = (AdminManager) currentUser.getPrincipal();
		return user == null ? null : user.getManagerId();
	}

	public static AdminManager getLoginUser() {
		try {
			Subject currentUser = SecurityUtils.getSubject();

			AdminManager identityUser = (AdminManager) currentUser
					.getPrincipal();
			AdminManager user = adminManagerSV.queryById(identityUser.getManagerId());

			return user;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void login(String username, String password,
			boolean rememberMe) {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			currentUser.logout();
		}
		UsernamePasswordToken token = new UsernamePasswordToken(username,
				password);
		token.setRememberMe(rememberMe);
		currentUser.login(token);
	}

	public static void logout() {
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
	}

}
